/*************************
**** Survey Library*******
*****Author: hieulv68******
***************************/


var Survey = {
	path: "http://localhost/khaosatviet/",
  l: 0,
  flagEditorTitle: false,
  saveQ: false,
  	
	/*Delete question when click 'xoa' link */
	delQuestion: function(idDel,idProject){
    this.idDel = idDel;
    this.idProject = idProject;
    $('#alert-del').data('id', this.idDel).modal('show');
    $('#btnYes').click(function() {
        $('#alert-del').modal('hide');
        this.idDel = idDel;
        this.idProject = idProject;
        $.ajax(
        {
           type: "POST",
           url: "../member/createSurvey/ajaxDelQuestion.ksv",
           data: {idDel:this.idDel, idProject:this.idProject},
           cache: false,
        
           success: function(rs)
           {
              $('.ques'+rs).fadeOut('slow', function() {$(this).remove();});
              if ($('#content-survey li').length <= 1) {
                $( "#content-survey ol").append("<li class='placeholder'><div>Bạn chưa tạo câu hỏi nào!</div></li>");
              }
            }
        });
		  });
	},


  testEditable: function(){
   
    //toggle `popup` / `inline` mode
    $.fn.editable.defaults.mode = 'popup';     
    
    //make username editable
    $('#project13').editable();   
  },
  /*pre edit projectName*/
  preEditProject: function(){
    $('#editProject').show();
    $('#projectName').hide();
    $('#edit-sur').hide();
  },

  /* Edit project */
  editProject: function(){
    this.idProject = $('#editProject input').attr('id');
    this.nameProject = $('#editProject input').val();
    $.ajax({
       type: "POST",
       url: this.path+"member/createSurvey/ajaxEditProject.ksv",
       data: {idProject:this.idProject,nameProject:this.nameProject},
       cache: false,
       success: function(data)
       {
        $('#editProject').hide();
        $('#projectName').show();
        $('#edit-sur').show();
        var rs = $.parseJSON(data);
        $('#projectName').html('<strong>'+rs[0].survey_name+'</strong>');
       }
    });
  },

  //procces and save data after editting a question
  proccessAndSaveQ: function(tit = false, addAns = false, save = false, idProject = false, typeQ='', exit= false,edit=false){
    this.tit = tit;
    this.addAns = addAns;
    this.save = save;
    this.idProject = idProject;
    this.typeQ = typeQ;
    this.exit = exit;
    this.edit = edit;
    $(document).on('click','.del-ans',function(){ // If click Del Ans
      $(this).parent().fadeOut('slow', function(){$(this).remove();});
    });
    if(this.tit == 1){ // If click swicth to text editor
      var c = $('#edit-title').val();
      $('#edit-title').remove();
      $('#edit-title-editor').html(c);
      $('#editor').show();
      $('.editor-ques').hide();
      this.flagEditorTitle = true;
    }else if(this.addAns == 1){ // If click 'Add Ans' button
      var id = parseInt($('#wap-ans').children(':last').attr('id'))+1;
      id = (id>=0)?id:0;
      var content = '<div id="'+id+'"><label class="help-inline">Lựa chọn '+(id+1)+': </label>&nbsp;&nbsp;<textarea rows="1" type="text" id="ans'+id+'" placeholder="Nhập lựa chọn ..."></textarea><button class="btn btn-link del-ans"><span class="btn-del">Xóa lựa chọn</span></button></div>';
      $('#wap-ans').append(content);
    }else if(this.save == 1){ // If click 'Save Question' button
      if(this.flagEditorTitle==false){
        var title = $('#edit-title').val();
      }else if(this.flagEditorTitle == true){
        var title = $('#edit-title-editor').html();
      }
      var numAns = parseInt($('#wap-ans').children().length);
      var projectId = '';
      var content = '';
      var arr = new Array();
      for(var i = 0; i < numAns; i++){
        var ansId = $('#wap-ans').children().eq(i).attr('id');
        arr.push(ansId);
      }
      for(var i = 0; i < arr.length; i++){
        var valAns = $('#ans'+i).val();
        content += valAns;
       var j = i+1;
        if(($('#ans'+j).val() != '')&&(j < arr.length)&&(valAns != '')){
          content += ',';
        }
      }
      if(this.edit == ''){
        $('.loading').show();
        $.ajax({
          type: "POST",
           url: this.path+"member/createSurvey/ajaxInsertQuestion.ksv",
           data: {projectId:this.idProject, questionType:this.typeQ, title:title, ans:content, exit:this.exit},
           cache: false,
           
           success: function(data)
           {
              var rs = $.parseJSON(data);
              //$('.save-update').attr('id', rs[0].questionId);
             $('.alert-save').show();
              $('.loading').hide();
        
            if(rs[0].exit == 1){
              window.location = rs[0].path+'tao-cau-hoi-khao-sat/'+rs[0].surId;
            }
           }
        });
         
      }else{
        var idQ = $('.save-update').attr('id');
        $('.loading').show();

        $.ajax({
          type: "POST",
           url: this.path+"member/createSurvey/ajaxUpadeContentQuestion.ksv",
           data: {idQuestion:idQ, title:title, ans:content},
           cache: false,
           success: function(data)
           {
              $('.alert-save').show();
              $('.loading').hide();
           }
        });
      }
      
    }
    
  },





  //autoload question by ajax
  listQuestion: function(idProject){
    this.idProject = idProject;
    $('.loading').show();
    $.ajax({
      type: 'POST',
      url: "../member/createSurvey/ajaxShowQuestion.ksv",
      data: {idProject:this.idProject},
      cache: false,
      success: function(data){
        $('.loading').hide();
        var rs = $.parseJSON(data);
        if(rs.length > 0){
          $( "#content-survey ol").find( ".placeholder" ).remove();
          for(var i = 0; i< rs.length; i++){
            var content = rs[i].answer; 

            var arr = content.split(',');
            //var c = 'abc,qsd'; var a = c.split(',');
            //alert(a.length);
             switch(rs[i].answer_type){
              case('radio'):
                $( "#content-survey ol").append('<li id="sort_'+rs[i].sort+'" class="ques'+rs[i].question_id+'"><div class="wap-question"><h4 id="title'+rs[i].question_id+'" class="survey-title">'+rs[i].title+'</h4>'+Survey.displayAnsQues(arr,'radio',rs[i].question_id)+'<div class="text-right"><small><a href="sua/'+rs[0].survey_id+'/'+rs[0].question_id+'/'+rs[0].answer_type+'"><span class="btn-edit"></span> Sửa</a> &nbsp;&nbsp; <a href=""><span class="btn-copy"></span> Sao chép</a> &nbsp;&nbsp; <button id="'+rs[i].question_id+'" class="btn-link del-ques del" onclick="Survey.delQuestion(this.id,'+rs[0].survey_id+'); return false;"><span class="btn-del"></span> Xóa</button></small></div><hr></div></li>');
                break;
              case('checkbox'):
                $( "#content-survey ol").append('<li id="sort_'+rs[i].sort+'" class="ques'+rs[i].question_id+'"><div class="wap-question"><h4 id="title'+rs[i].question_id+'" class="survey-title">'+rs[i].title+'</h4>'+Survey.displayAnsQues(arr,'checkbox',rs[i].question_id)+'<div class="text-right"><small><a href="sua/'+rs[0].survey_id+'/'+rs[0].question_id+'/'+rs[0].answer_type+'"><span class="btn-edit"></span> Sửa</a> &nbsp;&nbsp; <a href=""><span class="btn-copy"></span> Sao chép</a> &nbsp;&nbsp; <button id="'+rs[i].question_id+'" class="btn-link del-ques del" onclick="Survey.delQuestion(this.id,'+rs[0].survey_id+'); return false;"><span class="btn-del"></span> Xóa</button></small></div><hr></div></li>');
                break;
              case('textbox'):
                $( "#content-survey ol").append('<li id="sort_'+rs[i].sort+'" class="ques'+rs[i].questionId+'"><div class="wap-question"><h4 id="title'+rs[i].questionId+'" class="survey-title">'+rs[i].title+'</h4>'+Survey.displayAnsQues(arr,'checkbox',rs[i].question_id)+'<div class="text-right"><small><a href="sua/'+rs[0].survey_id+'/'+rs[0].question_id+'/'+rs[0].answer_type+'"><span class="btn-edit"></span> Sửa</a> &nbsp;&nbsp; <a href=""><span class="btn-copy"></span> Sao chép</a> &nbsp;&nbsp; <button id="'+rs[i].question_id+'" class="btn-link del-ques del" onclick="Survey.delQuestion(this.id,'+rs[0].survey_id+'); return false;"><span class="btn-del"></span> Xóa</button></small></div><hr></div></li>');
                break;
              case('textarea'):
                $("#content-survey ol").append('<li id="sort_'+rs[i].sort+'" class="ques'+rs[i].questionId+'"><div class="wap-question"><a id="'+rs[i].questionId+'" href="#" class="my-question"><h5 id="title'+rs[i].questionId+'" class="survey-title">'+rs[i].questionTitle+'</h5><small id="desc'+rs[i].questionId+'" class="des-sur">'+rs[i].questionDes+'</small><div><label class="textarea"><textarea rows="4" name="are1" readonly></textarea></label></div></a><div class="text-right"><small><button class="edit-ques btn-link" act="'+rs[i].questionId+'"><span class="btn-edit"></span> Sửa</button>&nbsp;&nbsp;<a href=""><span class="btn-copy"></span> Sao chép</a> &nbsp;&nbsp; <a id="'+rs[i].questionId+'" class="del-ques del" href="javascript:void(0)" onclick="Survey.delQuestion(this.id); return false;"><span class="btn-del"></span>Xóa</a></small></div><hr></div></li>');
                break;
              default:
                $( "#content-survey ol").append("<li>no understand</li>");
             }
              $('input.control').prettyCheckable();

          }
        }
      }
    })
  },
  // Display answers of question
  displayAnsQues: function(arr,control,idQuestion){
    this.arr = arr;
    this.control = control;
    this.idQuestion = idQuestion;
    var len = arr.length;
    result = '';
    if(len > 0){
      if(this.control=='radio'){
        for(var i = 0; i < len; i++){
          if(this.arr[i] != ''){
            result += '<div class="selection'+i+'"><input class="control" type="radio" name="radio" data-label="'+this.arr[i]+'" disabled></div>';
          }
        }

      }else if(this.control=='checkbox'){
        for(var i = 0; i < len; i++){
          result += '<div><label class="'+i+'"><input class="control" type="checkbox" name="checkbox" data-label="'+this.arr[i]+'" disabled></div>';
        }
      }
      
    }
    return result;
  },
  // Display answers of question in edit
  displayAnsQuesEdit: function(arr,idQ,contentQ){
    this.arr = arr;
    this.idQ = idQ;
    this.contentQ = contentQ;
    var content = contentQ;
    var id = this.idQ;
    var len = arr.length;
    l = len; 
    var result = '';
    if(len != 1){
      for(var i = 0; i < len; i++){
        if(this.arr[i] != ''){
            result += '<div class="input-append selection'+i+'"><input numAns='+len+' id="ans'+i+'" class="span12" id="appendedInputButton" type="text" value="'+this.arr[i]+'"><button id = "del-select-'+i+'" class="btn" type="button" onclick="Survey.delSelection('+id+', '+i+')"><img src="http://localhost/hieu/media/icon/DeleteRed2.png" alt="Xóa lựa chọn"></button></div>';
          }
        }
    }
    
    $(document).on('click','#add-ans'+id,function(){
      result += $('#selectAns').children(':first').append('<div class="input-append selection'+l+'"><input numAns='+len+' id="ans'+l+'" class="span12" id="appendedInputButton" type="text" value="Thêm lựa chọn"><button id = "del-select-'+l+'" class="btn" type="button" onclick="Survey.delSelection('+id+', '+l+')"><img src="http://localhost/hieu/media/icon/DeleteRed2.png" alt="Xóa lựa chọn"></button></div>');
      result += $('.wap-question #'+id).append('<div class="selection'+l+'"><label class="radio"><input type="radio" name="radio" readonly><p class="ans'+l+''+id+'">Thêm lựa chọn</p></label></div>');
      var arr = content.split(',');
      var c = arr.length;
      if(c == 1){
        content = content+'Thêm lựa chọn';
      }else{
        content = content+',Thêm lựa chọn';
      }
      
      l = l+1;
      $.ajax({
      type: 'POST',
      url: "../member/createSurvey/ajaxUpadeContentQuestion.html",
      data: {idQuestion:id,content:content},
      cache: false,
      success: function(){}
      });
      l = len;
    });
    return result;
  },
  //Delete a selection of question
  delSelection: function(idQuestion,pos){
    this.idQuestion = idQuestion;
    this.pos = pos;
    $.ajax({
      type: 'POST',
      url: "../member/createSurvey/ajaxDelContentQuestion.html",
      data: {idQuestion:this.idQuestion,pos:this.pos},
      cache: false,
      success: function(data){
        var data = $.parseJSON(data);
        $('.selection'+data[0].pos).fadeOut('slow', function() {$(this).remove();});
      }
    });
     
  },
  
  //edit question
  /*editQuestion: function(idQuestion){
    this.idQuestion = idQuestion;
   $('#option').empty();
    $.ajax({
      type: 'POST',
      url: "../member/createSurvey/ajaxShowEditQuestion.html",
      data: {idQuestion:this.idQuestion},
      cache: false,
      success: function(data){
        var t = $.parseJSON(data);
        var listQuestionType = {"radio":"Câu hỏi lựa chọn","checkbox":"Câu hỏi checkbox","textbox":"Câu hỏi văn bản ngắn","textarea":"Câu hỏi văn bản dài"};
        //var arr = JSON.parse(listQuestionType);
        var editContentQues = '<p class="text-success"><strong>Các thuộc tính</strong></p>';
          editContentQues += '<p><strong><small>Loại:</small></strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
          editContentQues +=   '<select class="span8">';
        $.each(listQuestionType, function(key, value) {
          if(key == t[0].questionType){
            editContentQues +=     '<option value="'+key+'" selected="selected"><small>'+value+'</small></option>';
          }else{
            editContentQues +=     '<option value="'+key+'"><small>'+value+'</small></option>';
          }
        });

          editContentQues +=   '</select>';
          editContentQues += '</p>';
          editContentQues += '<strong>Tiêu đề câu hỏi:</strong>';
          editContentQues += '<textarea rows="1" id="edit-title-ques">'+t[0].questionTitle+'</textarea>';
          editContentQues += '<div class="editor-ques"><button class="btn-link"><span class="btn-editor"></span>Mở trình soạn thảo trực quan</button></div>';
          editContentQues += '<div><strong>Mô tả:</strong></div>';
          editContentQues += '<textarea rows="1" id="edit-desc-ques">Mô tả</textarea>';
          editContentQues += '<div class="editor-desc"><button class="btn-link"><span class="btn-editor"></span>Mở trình soạn thảo trực quan</button></div>';
          editContentQues += '<div class="accordion" id="accordion2">';
          editContentQues +=   '<div class="accordion-group">';
          editContentQues +=     '<div class="accordion-heading">';
          editContentQues +=       '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#selectAns">';
          editContentQues +=         '<strong>Các lựa chọn</strong>';
          editContentQues +=       '</a>';
          editContentQues +=     '</div>';
          editContentQues +=     '<div id="selectAns" class="accordion-body collapse in">';
          editContentQues +=       '<div class="accordion-inner">';
          var content = t[0].questionContent; 
          var arr = content.split(',');
          editContentQues +=         Survey.displayAnsQuesEdit(arr,t[0].questionId,t[0].questionContent);
          
          editContentQues +=       '</div>';
          editContentQues +=       '<div class="btn-option"><button id="add-ans'+t[0].questionId+'" class="btn"><span class="btn-add"></span>Thêm</button>&nbsp;&nbsp;<button class="btn"><span class="btn-copy">Sao chép</span></button></div>';
          editContentQues +=     '</div>';
          editContentQues +=   '</div>';
          editContentQues +=   '<div class="accordion-group">';
          editContentQues +=     '<div class="accordion-heading">';
          editContentQues +=       '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">';
          editContentQues +=         '<strong>Hiển thị</strong>';
          editContentQues +=       '</a>';
          editContentQues +=     '</div>';
          editContentQues +=     '<div id="collapseTwo" class="accordion-body collapse">';
          editContentQues +=       '<div class="accordion-inner">';
          editContentQues +=         'Anim pariatur cliche...';
          editContentQues +=       '</div>';
          editContentQues +=     '</div>';
          editContentQues +=   '</div>';
          editContentQues +=   '<div class="accordion-group">';
          editContentQues +=     '<div class="accordion-heading">';
          editContentQues +=       '<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">';
          editContentQues +=         '<strong>Các tùy chọn</strong>';
          editContentQues +=       '</a>';
          editContentQues +=     '</div>';
          editContentQues +=     '<div id="collapseTwo" class="accordion-body collapse">';
          editContentQues +=       '<div class="accordion-inner">';
          editContentQues +=         'Anim pariatur cliche...';
          editContentQues +=       '</div>';
          editContentQues +=     '</div>';
          editContentQues +=   '</div>';
          editContentQues += '</div>';
         
        if (t.length != 0){
          $('#option').append(editContentQues);
          //
          
          $(document).on('click','.editor-desc',function(){// Show popup editor of description
            $('#editor-popup').data('id', '#edit-desc-ques').modal('show');
            $('#content-editor').html($('#edit-desc-ques').val());
            $('#btnok').click(function() {
              $('#editor-popup').modal('hide');
              $('#edit-desc-ques').html($('#content-editor').html());
              $('#desc'+t[0].questionId).html($('#edit-desc-ques').text());
            });
          });
        }else{
          $('#option').append('Không có dữ liệu!');
        }
      }
    });
  },*/
  //active question type
  activeQuestionType: function(id){
    this.id = id;
    var listQuestionType = [{"radio":"Câu hỏi lựa chọn"},{"checkbox":"Câu hỏi checkbox"},{"textbox":"Câu hỏi văn bản ngắn"},{"textarea":"Câu hỏi văn bản dài"}];
    var arr = parseJSON(listQuestionType);
  }
};
$(document).ready(function(){
 // $('input.myClass').prettyCheckable();
  
  
  $(document).on('focus','#edit-title-ques',function(){ //open a text editor link for question title
    $('.editor-ques').show("slow");
  });
  $(document).on('focusout','#edit-title-ques',function(){ 
    $('.editor-ques').hide("slow");
  });
  $(document).on('focus','#edit-desc-ques',function(){ //open a text editor link for question description
    $('.editor-desc').show("slow");
  });
  $(document).on('focusout','#edit-desc-ques',function(){ 
    $('.editor-desc').hide("slow");
  });
});
